#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
攻击服务器数据销毁器 - 彻底销毁敏感数据和操作痕迹
当被蓝队发现后，在攻击服务器上执行的紧急数据销毁脚本

销毁范围：
1. 所有操作日志和报告
2. 攻击工具和脚本
3. 目标信息和凭据
4. 配置文件和密钥
5. 临时文件和缓存
6. 数据库和存储
7. 网络配置和历史
8. 系统痕迹和元数据
"""

import os
import sys
import glob
import time
import shutil
import subprocess
import tempfile
import random
import string
from datetime import datetime
from pathlib import Path

def execute_command(cmd, timeout=10):
    """安全执行命令"""
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, 
                              text=True, timeout=timeout)
        return result.returncode == 0, result.stdout, result.stderr
    except subprocess.TimeoutExpired:
        return False, "", "命令超时"
    except Exception as e:
        return False, "", str(e)

def secure_delete_file(file_path, passes=3):
    """安全删除文件（多次覆写）"""
    try:
        if not os.path.exists(file_path):
            return True
            
        file_size = os.path.getsize(file_path)
        
        # 多次覆写
        for i in range(passes):
            with open(file_path, 'wb') as f:
                if i == 0:
                    # 第一次用随机数据覆写
                    f.write(os.urandom(file_size))
                elif i == 1:
                    # 第二次用零覆写
                    f.write(b'\x00' * file_size)
                else:
                    # 第三次用0xFF覆写
                    f.write(b'\xFF' * file_size)
            f.flush()
            os.fsync(f.fileno())
        
        # 最后删除文件
        os.remove(file_path)
        return True
        
    except Exception as e:
        print(f"  ❌ 安全删除失败 {file_path}: {e}")
        try:
            # 备用删除方案
            os.remove(file_path)
            return True
        except:
            return False

def secure_delete_directory(dir_path):
    """安全删除目录"""
    try:
        if not os.path.exists(dir_path):
            return True
            
        # 递归删除目录中的所有文件
        for root, dirs, files in os.walk(dir_path, topdown=False):
            for file_name in files:
                file_path = os.path.join(root, file_name)
                secure_delete_file(file_path)
            
            for dir_name in dirs:
                dir_full_path = os.path.join(root, dir_name)
                try:
                    os.rmdir(dir_full_path)
                except:
                    pass
        
        # 删除根目录
        try:
            os.rmdir(dir_path)
            return True
        except:
            try:
                shutil.rmtree(dir_path)
                return True
            except:
                return False
                
    except Exception as e:
        print(f"  ❌ 目录删除失败 {dir_path}: {e}")
        return False

def destroy_operation_logs():
    """销毁操作日志"""
    print("📝 销毁操作日志...")
    
    log_patterns = [
        'logs/*.log',
        'logs/*.txt',
        '*.log',
        'reports/*.json',
        'reports/*.html',
        'reports/*.md',
        'reports/*.txt',
        'tests/reports/*',
        'deployment/logs/*',
        'modules/*/logs/*'
    ]
    
    destroyed_count = 0
    
    for pattern in log_patterns:
        try:
            files = glob.glob(pattern, recursive=True)
            for file_path in files:
                if secure_delete_file(file_path):
                    print(f"  ✅ 销毁日志: {file_path}")
                    destroyed_count += 1
        except Exception as e:
            print(f"  ❌ 日志销毁失败 {pattern}: {e}")
    
    # 销毁整个日志目录
    log_dirs = ['logs', 'reports', 'tests/reports']
    for log_dir in log_dirs:
        if os.path.exists(log_dir):
            if secure_delete_directory(log_dir):
                print(f"  ✅ 销毁日志目录: {log_dir}")
                destroyed_count += 1
    
    print(f"  📊 总计销毁日志: {destroyed_count} 项")

def destroy_attack_tools():
    """销毁攻击工具"""
    print("🔧 销毁攻击工具...")
    
    tool_dirs = [
        'tools',
        'exploits',
        'payloads',
        'scripts',
        'modules/exploits',
        'modules/persistence',
        'modules/evasion',
        'modules/security',
        'examples'
    ]
    
    destroyed_count = 0
    
    for tool_dir in tool_dirs:
        if os.path.exists(tool_dir):
            if secure_delete_directory(tool_dir):
                print(f"  ✅ 销毁工具目录: {tool_dir}")
                destroyed_count += 1
    
    # 销毁可执行脚本
    script_patterns = [
        '*.py',
        '*.sh',
        '*.ps1',
        '*.bat',
        '*.exe'
    ]
    
    for pattern in script_patterns:
        try:
            files = glob.glob(pattern)
            for file_path in files:
                # 跳过当前销毁脚本
                if file_path == __file__:
                    continue
                    
                if secure_delete_file(file_path):
                    print(f"  ✅ 销毁脚本: {file_path}")
                    destroyed_count += 1
        except:
            pass
    
    print(f"  📊 总计销毁工具: {destroyed_count} 项")

def destroy_sensitive_data():
    """销毁敏感数据"""
    print("🔐 销毁敏感数据...")
    
    sensitive_patterns = [
        'config/*.json',
        'config/*.conf',
        'config/*.ini',
        '*.key',
        '*.pem',
        '*.crt',
        '*.p12',
        'credentials*',
        'targets*',
        'passwords*',
        'secrets*',
        'tokens*',
        'keys*'
    ]
    
    destroyed_count = 0
    
    for pattern in sensitive_patterns:
        try:
            files = glob.glob(pattern, recursive=True)
            for file_path in files:
                if secure_delete_file(file_path):
                    print(f"  ✅ 销毁敏感文件: {file_path}")
                    destroyed_count += 1
        except:
            pass
    
    # 销毁配置目录
    config_dirs = ['config', 'templates', 'ansible']
    for config_dir in config_dirs:
        if os.path.exists(config_dir):
            if secure_delete_directory(config_dir):
                print(f"  ✅ 销毁配置目录: {config_dir}")
                destroyed_count += 1
    
    print(f"  📊 总计销毁敏感数据: {destroyed_count} 项")

def destroy_database_files():
    """销毁数据库文件"""
    print("🗄️ 销毁数据库文件...")
    
    db_patterns = [
        '*.db',
        '*.sqlite',
        '*.sqlite3',
        '*.mdb',
        'data/*.json',
        'data/*.xml',
        'cache/*',
        'tmp/*'
    ]
    
    destroyed_count = 0
    
    for pattern in db_patterns:
        try:
            files = glob.glob(pattern, recursive=True)
            for file_path in files:
                if secure_delete_file(file_path):
                    print(f"  ✅ 销毁数据库: {file_path}")
                    destroyed_count += 1
        except:
            pass
    
    print(f"  📊 总计销毁数据库: {destroyed_count} 项")

def destroy_temp_files():
    """销毁临时文件"""
    print("🗑️ 销毁临时文件...")
    
    temp_locations = [
        '/tmp/privilege*',
        '/tmp/attack*',
        '/tmp/red*',
        '/tmp/exploit*',
        '/var/tmp/tools*',
        '~/.cache/privilege*',
        '~/.local/share/privilege*',
        'temp/*',
        'tmp/*',
        '__pycache__',
        '*.pyc',
        '*.pyo',
        '.pytest_cache'
    ]
    
    destroyed_count = 0
    
    for location in temp_locations:
        expanded_path = os.path.expanduser(location)
        try:
            if '*' in expanded_path:
                files = glob.glob(expanded_path)
                for file_path in files:
                    if os.path.isfile(file_path):
                        if secure_delete_file(file_path):
                            destroyed_count += 1
                    elif os.path.isdir(file_path):
                        if secure_delete_directory(file_path):
                            destroyed_count += 1
            else:
                if os.path.exists(expanded_path):
                    if os.path.isfile(expanded_path):
                        if secure_delete_file(expanded_path):
                            destroyed_count += 1
                    elif os.path.isdir(expanded_path):
                        if secure_delete_directory(expanded_path):
                            destroyed_count += 1
        except:
            pass
    
    print(f"  📊 总计销毁临时文件: {destroyed_count} 项")

def clear_system_traces():
    """清理系统痕迹"""
    print("🧹 清理系统痕迹...")
    
    # 清理bash历史
    history_files = [
        '~/.bash_history',
        '~/.zsh_history',
        '~/.history'
    ]
    
    for hist_file in history_files:
        expanded_path = os.path.expanduser(hist_file)
        if os.path.exists(expanded_path):
            try:
                # 生成虚假的正常历史记录
                fake_history = [
                    "ls -la",
                    "cd /home",
                    "ps aux",
                    "top",
                    "df -h",
                    "free -m",
                    "uname -a",
                    "whoami",
                    "pwd",
                    "exit"
                ]
                
                with open(expanded_path, 'w') as f:
                    for cmd in fake_history:
                        f.write(f"{cmd}\n")
                
                print(f"  ✅ 伪造历史记录: {hist_file}")
            except:
                pass
    
    # 清理当前会话历史
    execute_command("history -c")
    execute_command("history -w")
    
    # 清理系统日志中的相关条目
    try:
        log_files = ['/var/log/auth.log', '/var/log/syslog', '/var/log/messages']
        for log_file in log_files:
            if os.path.exists(log_file):
                # 移除包含敏感关键词的日志行
                execute_command(f"sed -i '/privilege/d' {log_file}")
                execute_command(f"sed -i '/attack/d' {log_file}")
                execute_command(f"sed -i '/exploit/d' {log_file}")
                execute_command(f"sed -i '/backdoor/d' {log_file}")
        print("  ✅ 清理系统日志条目")
    except:
        pass

def overwrite_free_space():
    """覆写磁盘空闲空间"""
    print("💾 覆写磁盘空闲空间...")
    
    try:
        # 创建大文件填充空闲空间
        temp_dir = tempfile.mkdtemp()
        temp_file = os.path.join(temp_dir, 'overwrite.tmp')
        
        print("  🔄 正在覆写空闲空间（这可能需要一些时间）...")
        
        # 写入随机数据直到磁盘满
        try:
            with open(temp_file, 'wb') as f:
                while True:
                    f.write(os.urandom(1024 * 1024))  # 1MB chunks
        except OSError:
            # 磁盘满了，这是预期的
            pass
        
        # 删除临时文件
        if os.path.exists(temp_file):
            os.remove(temp_file)
        os.rmdir(temp_dir)
        
        print("  ✅ 空闲空间覆写完成")
        
    except Exception as e:
        print(f"  ❌ 空闲空间覆写失败: {e}")

def forge_file_metadata():
    """伪造文件元数据"""
    print("📅 伪造文件元数据...")
    
    # 修改剩余文件的时间戳
    try:
        # 设置为一个月前的随机时间
        month_ago = time.time() - (30 * 24 * 3600)
        random_time = month_ago + random.randint(0, 7 * 24 * 3600)
        
        # 查找所有剩余文件
        for root, dirs, files in os.walk('.'):
            for file_name in files:
                file_path = os.path.join(root, file_name)
                try:
                    os.utime(file_path, (random_time, random_time))
                except:
                    pass
        
        print("  ✅ 文件时间戳伪造完成")
        
    except Exception as e:
        print(f"  ❌ 元数据伪造失败: {e}")

def create_decoy_files():
    """创建诱饵文件"""
    print("🎭 创建诱饵文件...")
    
    try:
        # 创建一些看起来正常的文件
        decoy_files = {
            'README.md': '# 系统维护工具\n\n这是一个系统维护和监控工具集合。\n',
            'install.sh': '#!/bin/bash\necho "安装系统监控工具..."\n',
            'config.ini': '[settings]\nlog_level=INFO\noutput_dir=/var/log\n',
            'monitor.py': '#!/usr/bin/env python3\n# 系统监控脚本\nimport os\nprint("系统监控中...")\n'
        }
        
        for filename, content in decoy_files.items():
            try:
                with open(filename, 'w') as f:
                    f.write(content)
                
                # 设置旧的时间戳
                old_time = time.time() - (60 * 24 * 3600)  # 60天前
                os.utime(filename, (old_time, old_time))
                
                print(f"  ✅ 创建诱饵文件: {filename}")
            except:
                pass
                
    except Exception as e:
        print(f"  ❌ 诱饵文件创建失败: {e}")

def final_system_cleanup():
    """最终系统清理"""
    print("🔥 执行最终系统清理...")
    
    # 清理内存
    try:
        execute_command("sync")
        execute_command("echo 3 > /proc/sys/vm/drop_caches")
        print("  ✅ 清理系统缓存")
    except:
        pass
    
    # 清理网络连接历史
    try:
        execute_command("arp -d -a")
        print("  ✅ 清理ARP缓存")
    except:
        pass
    
    # 清理DNS缓存
    try:
        execute_command("systemctl flush-dns")
        print("  ✅ 清理DNS缓存")
    except:
        pass
    
    # 重置网络统计
    try:
        execute_command("ip -s -s neigh flush all")
        print("  ✅ 重置网络统计")
    except:
        pass

def self_destruct():
    """自毁程序"""
    print("💥 启动自毁程序...")
    
    try:
        script_path = os.path.abspath(__file__)
        
        # 创建自毁脚本
        self_destruct_script = f"""#!/bin/bash
sleep 3
shred -u '{script_path}' 2>/dev/null || rm -f '{script_path}'
rm -f '$0'
"""
        
        temp_script = '/tmp/.cleanup_final.sh'
        with open(temp_script, 'w') as f:
            f.write(self_destruct_script)
        
        os.chmod(temp_script, 0o755)
        
        # 启动自毁脚本
        subprocess.Popen(['/bin/bash', temp_script], 
                        stdout=subprocess.DEVNULL, 
                        stderr=subprocess.DEVNULL)
        
        print("  ✅ 自毁程序已启动")
        
    except Exception as e:
        print(f"  ❌ 自毁程序失败: {e}")

def main():
    """主销毁流程"""
    start_time = time.time()
    
    print("🔥" + "="*50)
    print("🔥 攻击服务器数据销毁系统")
    print("🔥 开始执行彻底数据销毁...")
    print("🔥" + "="*50)
    
    # 执行销毁步骤
    steps = [
        ("销毁操作日志", destroy_operation_logs),
        ("销毁攻击工具", destroy_attack_tools),
        ("销毁敏感数据", destroy_sensitive_data),
        ("销毁数据库文件", destroy_database_files),
        ("销毁临时文件", destroy_temp_files),
        ("清理系统痕迹", clear_system_traces),
        ("伪造文件元数据", forge_file_metadata),
        ("创建诱饵文件", create_decoy_files),
        ("覆写磁盘空闲空间", overwrite_free_space),
        ("最终系统清理", final_system_cleanup)
    ]
    
    for step_name, step_func in steps:
        try:
            print(f"\n📋 执行: {step_name}")
            step_func()
            print(f"✅ 完成: {step_name}")
        except Exception as e:
            print(f"❌ 失败: {step_name} - {e}")
    
    total_time = time.time() - start_time
    
    print("\n" + "="*50)
    print("📊 数据销毁完成总结")
    print("="*50)
    print(f"⏱️  总执行时间: {total_time:.2f}秒")
    print("✅ 攻击服务器数据销毁完成")
    print("⚠️  建议立即关闭服务器")
    print("⚠️  建议更换所有网络设备")
    print("⚠️  建议重新部署整个基础设施")
    print("="*50)
    
    # 最后执行自毁
    print("\n🚨 准备执行自毁程序...")
    time.sleep(2)
    self_destruct()
    
    print("💥 数据销毁系统即将退出...")
    time.sleep(1)

if __name__ == "__main__":
    main()